# -*- coding: utf-8 -*-

import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urlencode, datetime
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanPanzhihuaPolicy(BaseTaxPolicySpider):
    name = 'sichuan_panzhihua2_policy'

    province = '四川省'
    city = '攀枝花市'
    # county = '滑县'
    park = ''

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['攀枝花市发展和改革委员会', "", "http://www.panzhihua.gov.cn/zfxxgk1/zc/szfwj/index.shtml"],
            ['攀枝花市东区人民政府', "东区", "http://www.scdongqu.gov.cn/zfxxgk/fdzdgknr/lzyj/qzfwj1/index.shtml"],
            ['攀枝花市西区人民政府', "西区", "http://www.pzhsxq.gov.cn/zwgk/zfwj/qzfwj/index.shtml"],
            ['攀枝花市西区人民政府', "西区", "http://www.pzhsxq.gov.cn/zwgk/zfwj/qzfbwj/index.shtml"],
            ['攀枝花市仁和区人民政府', "仁和区", "http://www.screnhe.gov.cn/zfxxgk/fdzdgknr/lzyj/qzfwj1/index.shtml"],
            ['攀枝花市米易县人民政府', "米易县", "http://www.scmiyi.gov.cn/zfxxgk/fdzdgknr/lzyj/xzfwj/index.shtml"],
            ['攀枝花市米易县人民政府', "米易县", "http://www.scmiyi.gov.cn/zfxxgk/fdzdgknr/lzyj/xzfbwj/index.shtml"],
            ['攀枝花市盐边县人民政府', "盐边县", "http://www.scyanbian.gov.cn/zwgk/fggw/bmwj/index.shtml"],
            ['攀枝花市盐边县人民政府', "盐边县", "http://www.scyanbian.gov.cn/zwgk/fggw/xzfwj/index.shtml"],
            ['攀枝花市盐边县人民政府', "盐边县", "http://www.scyanbian.gov.cn/zwgk/fggw/xzfbwj/index.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//div[@class='gknr_list']//li[@class='hui']//a[(contains(@href, 'shtml') and @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=5] | "
            "//ul[contains(@class, 'clearfix') or @class='ul_1']//li//a[(contains(@href, 'shtml') and @target) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=5]"
        )

        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])

            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if 'htm' not in item['source_url']:
                continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        # if self.get_next or self.get_next == '0':
        page = response.meta.get('page', 1)
        next_url = response.xpath(
            """//a[text()='下页' or ./text()='下页>' or text()='>>' or text()='»' or contains(./text(), '下一页') or text()='下一页»']/@href""").re_first("javascript:window.location='(.*?)'") or response.xpath(
            """//a[text()='下页' or ./text()='下页>' or text()='>>' or text()='»' or contains(./text(), '下一页') or text()='下一页»']/@href""").get()
        if not next_url:
            next_url = response.xpath(f"""//b[text()='{page}']/following::a/@href""").get()
        if next_url and next_url not in ['javascript:void(0);'] and response.urljoin(next_url) != response.url:
            print(response.url, f'共{response.xpath("//label/text()").getall()}', 'next', next_url)
            yield response.follow(next_url, callback=self.parse_list, meta={'item': prev_item, "page": page + 1})
        else:
            # print(response.text)
            print(response.url, f'共{response.xpath("//label/text()").getall()}', 'not next_url')

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get() or response.xpath("/title/text()").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").re_first(r"\d{4}-\d{2}-\d{2}")
        print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_panzhihua2_policy".split())
